from selenium.webdriver import Chrome
from selenium.webdriver.common.by import By
import time

def window_scrollBy(driver, stop_length, step_length):
    '''
    :param driver: selenium对象
    :param stop_length: 一共拖拽的长度
    :param step_length: 每次拖拽的长度
    :return:
    '''
    while True:
        if stop_length <= step_length:
            driver.execute_script(f'window.scrollBy(0, {stop_length})')
            break
        # 拖拽滚动条
        driver.execute_script(f'window.scrollBy(0, {step_length})')
        # 获取剩余的拖拽长度
        stop_length -= step_length
        time.sleep(1)


if __name__ == '__main__':
    # 实例化
    driver = Chrome()
    # 访问网址
    driver.get('https://news.163.com/')
    stop_length = 30000  # 拖拽的高度
    step_length = 1000  # 拖拽的步长
    # 循环点击加载更多
    for i in range(1, 6):
        window_scrollBy(driver, stop_length, step_length)
        # 点击加载更多
        more = driver.find_element(By.XPATH, '//*[@id="index2016_wrap"]/div[3]/div[2]/div[3]/div[2]/div[5]/div/a[3]/div[1]/span')
        driver.execute_script('arguments[0].click()', more)
        print(f'第{i}次点击加载更多')
        time.sleep(1)
    # 加载更多点击完毕
    # 获取页面源代码
    page = driver.page_source
    print(page)
    time.sleep(30)